import 'package:flutter_hex_color/flutter_hex_color.dart';
import 'package:get/get.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:signage/app/data/models/board_element.dart';
import 'package:signage/app/data/models/cast_record_model.dart';
import 'package:signage/app/data/models/member_group_model.dart';
import 'package:signage/app/data/models/template_model.dart';
import 'package:signage/app/modules/device/add_device/controllers/add_device_controller.dart';
import 'package:signage/app/modules/device/add_device/views/add_device_view.dart';
import 'package:signage/app/modules/device/controllers/device_controller.dart';
import 'package:signage/app/modules/device/models/device_cached_info.dart';
import 'package:signage/app/modules/device/views/device_view.dart';
import 'package:signage/app/modules/template/views/template_view.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/services/bluetooth_service.dart';
import 'dart:convert';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/material.dart';
import 'package:signage/app/widgets/board_widget.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/device_list_item.dart';

class CastController extends GetxController {
  //TODO: Implement CastController

  final count = 0.obs;
  var sampleValue = 0.obs;
  Rx<TemplateModel?> templateModelA = Rx<TemplateModel?>(null);
  Rx<TemplateModel?> templateModelB = Rx<TemplateModel?>(null);
  RxList<MemberItem> selectedMembers = RxList<MemberItem>([]);
  RxString selectedGroupName = RxString('');
  final selectedGroupId = 0.obs;
  RxString meetingTitle = RxString('');
  final meetingTitleController = TextEditingController();
  @override
  void onInit() {
    super.onInit();
    meetingTitle.value = AppLocalizations.of(Get.context!)!
        .translate('meeting_date_title', params: {
      'year': DateTime.now().year.toString(),
      'month': DateTime.now().month.toString(),
      'day': DateTime.now().day.toString()
    });
    meetingTitleController.text = meetingTitle.value;
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;

  void touchSample(int index) {
    if (isSingleScrenn.value) {
      ToastUtils.show(AppLocalizations.of(Get.context!)!
          .translate('single_screen_no_switch'));
      return;
    }
    sampleValue.value = index;

    // Sync templates for AB same mode
    if (index == 0 && templateModelA.value != null) {
      templateModelB.value = templateModelA.value;
    } else if (index == 0 && templateModelB.value != null) {
      templateModelA.value = templateModelB.value;
    }

    // Clear B template for A-only mode
    if (index == 2) {
      templateModelB.value = null;
    }

    // Clear A template for B-only mode
    if (index == 3) {
      templateModelA.value = null;
    }

    print("当前选择了${sampleValue}");
    refresh();
  }

  void touchChooseList() {
    print("点击了选择名单");
    Get.toNamed(Routes.CHOOSE_LIST, arguments: {
      'templateA': templateModelA.value,
      'templateB': templateModelB.value,
      'mode': 'select', // 添加模式参数，表示选择模式
      'sampleValue': sampleValue.value // 添加 sampleValue
    })?.then((value) {
      print("value: ${value}");
      if (value != null && value['memberList'] != null) {
        selectedMembers.value = value['memberList'];
        selectedGroupName.value = value['groupName'] ?? '';
        selectedGroupId.value = value['groupId'] ?? 0;
        print("已选择成员列表: ${selectedMembers.length}人");
      }
    });
  }

  void selectTemplateA() async {
    final data = await Get.to(() => const TemplateView(source: 'picker'),
        arguments: {'side': 'A'});
    if (data != null) {
      final template = data as TemplateModel;
      if (selectedDevices.any((device) =>
          device.displayInfo[0].width.toString() !=
              template!.size.split('|')[1].trim().toString().split('X')[0] ||
          device.displayInfo[0].height.toString() !=
              template!.size.split('|')[1].trim().toString().split('X')[1])) {
        ToastUtils.showError('设备分辨率与模板不匹配');
        return;
      }

      templateModelA.value = template;

      // Sync B template if in AB same mode
      if (sampleValue.value == 0) {
        templateModelB.value = template;
      }

      print("选择了模板A: ${jsonEncode(template.toJson())}");
    }
  }

  void selectTemplateB() async {
    final data = await Get.to(() => const TemplateView(source: 'picker'),
        arguments: {'side': 'B'});
    if (data != null) {
      final template = data as TemplateModel;
      if (selectedDevices.any((device) =>
          device.displayInfo[0].width.toString() !=
              template!.size.split('|')[1].trim().toString().split('X')[0] ||
          device.displayInfo[0].height.toString() !=
              template!.size.split('|')[1].trim().toString().split('X')[1])) {
        ToastUtils.showError('设备分辨率与模板不匹配');
        return;
      }
      templateModelB.value = template;

      // Sync A template if in AB same mode
      if (sampleValue.value == 0) {
        templateModelA.value = template;
      }

      print("选择了模板B: ${jsonEncode(template.toJson())}");
    }
  }

  void viewMembers() {
    Get.toNamed(Routes.CHOOSE_LIST, arguments: {
      'memberList': selectedMembers,
      'groupName': selectedGroupName.value,
      'groupId': selectedGroupId.value,
      'mode': 'view' // 添加模式参数，表示查看模式
    });
  }

  void editMembers() {
    Get.toNamed(Routes.CHOOSE_LIST, arguments: {
      'memberList': selectedMembers,
      'groupName': selectedGroupName.value,
      'groupId': selectedGroupId.value,
      'templateA': templateModelA.value,
      'templateB': templateModelB.value,
      'mode': 'edit', // 添加模式参数，表示编辑模式
      'sampleValue': sampleValue.value // 添加 sampleValue
    })?.then((value) {
      if (value != null && value['memberList'] != null) {
        selectedMembers.value = value['memberList'];
        selectedGroupName.value = value['groupName'] ?? '';
        selectedGroupId.value = value['groupId'] ?? 0;
      }
    });
  }

  RxList<DeviceCachedInfo> selectedDevices = RxList<DeviceCachedInfo>([]);

  void selectDevice() async {
    Get.find<DeviceController>().onResumed();
    final data = await Get.to(() => const DeviceView(source: 'picker'),
        arguments: {'mode': 'select'});
    if (data != null) {
      if (data is List<DeviceCachedInfo>) {
        validateDeviceResolution(data);
      } else if (data is DeviceCachedInfo) {
        validateDeviceResolution([data]);
      }
    }
  }

  // 校验设备与模板分辨率是否匹配
  bool validateDeviceResolution(List<DeviceCachedInfo> devices) {
    // 验证每个新设备
    for (var device in devices) {
      // 如果存在A面模板，验证设备是否与A面模板匹配
      if (templateModelA.value != null) {
        if (device.displayInfo.any((d) =>
            d.width.toString() !=
                templateModelA.value!.size
                    .split('|')[1]
                    .trim()
                    .toString()
                    .split('X')[0] ||
            d.height.toString() !=
                templateModelA.value!.size
                    .split('|')[1]
                    .trim()
                    .toString()
                    .split('X')[1])) {
          ToastUtils.showError(AppLocalizations.of(Get.context!)!
              .translate('device_resolution_not_match_a'));
          return false;
        }
      }

      // 如果存在B面模板，验证设备是否与B面模板匹配
      if (templateModelB.value != null) {
        if (device.displayInfo.any((d) =>
            d.width.toString() !=
                templateModelB.value!.size
                    .split('|')[1]
                    .trim()
                    .toString()
                    .split('X')[0] ||
            d.height.toString() !=
                templateModelB.value!.size
                    .split('|')[1]
                    .trim()
                    .toString()
                    .split('X')[1])) {
          ToastUtils.showError(AppLocalizations.of(Get.context!)!
              .translate('device_resolution_not_match_b'));
          return false;
        }
      }

      devices.removeWhere((newDevice) => selectedDevices
          .any((existingDevice) => existingDevice.id == newDevice.id));

      if (selectedDevices.any((d) => d.id == device.id)) {
        ToastUtils.showError(AppLocalizations.of(Get.context!)!
            .translate('device_already_selected'));
        return false;
      }

      if (selectedDevices.any((d) =>
          d.displayInfo[0].width != device.displayInfo[0].width ||
          d.displayInfo[0].height != device.displayInfo[0].height)) {
        ToastUtils.showError(AppLocalizations.of(Get.context!)!
            .translate('device_resolution_not_match_selected'));
        return false;
      }
    }

    if (devices.first.displayInfo.length == 1) {
      isSingleScrenn.value = true;
      sampleValue.value = 2;
      templateModelB.value = null;
    } else {
      isSingleScrenn.value = false;
    }
    // 所有设备验证通过后，添加到已选设备列表
    selectedDevices.addAll(devices);
    return true;
  }

  final isSingleScrenn = false.obs;

  bool validateCastRequirements() {
    // 检查是否选择了设备
    if (selectedDevices.isEmpty) {
      ToastUtils.show(
          AppLocalizations.of(Get.context!)!.translate('please_select_device'));
      return false;
    }

    // 检查是否选择了名单
    if (selectedMembers.isEmpty) {
      ToastUtils.show(AppLocalizations.of(Get.context!)!
          .translate('please_select_members'));
      return false;
    }

    // 根据模板选择模式检查模板是否已选择
    switch (sampleValue.value) {
      case 0: // AB面相同
      case 2: // 仅A面
        if (templateModelA.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('please_select_template_a'));
          return false;
        }
        break;
      case 1: // AB面不同
        if (templateModelA.value == null || templateModelB.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('please_select_template_ab'));
          return false;
        }
        break;
      case 3: // 仅B面
        if (templateModelB.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('please_select_template_b'));
          return false;
        }
        break;
    }

    return true;
  }

  void startCasting() {
    if (!validateCastRequirements()) return; // 详细打印成员信息
    print('templateA: ${templateModelA.value?.toJson()}');
    print('templateB: ${templateModelB.value?.toJson()}');
    print('castMode: ${sampleValue.value}');
    Get.toNamed(Routes.CAST_PROGRESS, arguments: {
      'devices': selectedDevices,
      'templateA': templateModelA.value,
      'templateB': templateModelB.value,
      'members': selectedMembers,
      'meetingTitle': meetingTitle.value,
      'castMode': sampleValue.value,
      'groupId': selectedGroupId.value,
      'groupName': selectedGroupName.value,
    });
    // print('selectedDevices: ${selectedDevices.first.displayInfo[0].displayType}');
    // templateModelA.value?.convertToEpaper(
    //   '${templateModelA.value?.id}_${DateTime.now().millisecondsSinceEpoch}.bin',
    //   8,
    //   width: 480,
    //   height: 800,
    // );
  }

  void removeSelectedDevice(String id) {
    selectedDevices.removeWhere((device) => device.id == id);
  }

  bool validatePreviewRequirements() {
    // 检查是否选择了名单
    if (selectedMembers.isEmpty) {
      ToastUtils.show(AppLocalizations.of(Get.context!)!
          .translate('cast_select_members_first'));
      return false;
    }

    // 根据模板选择模式检查模板是否已选择
    switch (sampleValue.value) {
      case 0: // AB面相同
      case 2: // 仅A面
        if (templateModelA.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('cast_select_template_a'));
          return false;
        }
        break;
      case 1: // AB面不同
        if (templateModelA.value == null || templateModelB.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('cast_select_both_templates'));
          return false;
        }
        break;
      case 3: // 仅B面
        if (templateModelB.value == null) {
          ToastUtils.show(AppLocalizations.of(Get.context!)!
              .translate('cast_select_template_b'));
          return false;
        }
        break;
    }

    return true;
  }

  void preview() async {
    if (!validatePreviewRequirements()) return;
    print(selectedMembers.first.memberInfoList
            ?.where((e) => e.type == 'A' || e.type == 'AB')
            .map((e) => e.value ?? '')
            .toList() ??
        []);
    Get.dialog(
      barrierColor: Colors.black,
      Dialog(
        backgroundColor: Colors.black,
        insetPadding: EdgeInsets.zero,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final dialogWidth = constraints.maxWidth;
            final previewWidth = templateModelA.value?.width ??
                templateModelB.value?.width ??
                800;
            final templateHeight = templateModelA.value?.height ??
                templateModelB.value?.height ??
                480;
            final aspectRatio = previewWidth / templateHeight;
            print("aspectRatio: ${aspectRatio}");
            final previewHeight = dialogWidth / aspectRatio;
            print("dialogWidth: ${dialogWidth}");
            return SingleChildScrollView(
              child: Container(
                  width: dialogWidth,
                  height: constraints.maxHeight,
                  child: Stack(
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(height: 75.h),
                          if (sampleValue.value != 3 &&
                              templateModelA.value != null)
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  width: 104.w,
                                  height: 34.h,
                                  decoration: BoxDecoration(
                                    color:
                                        const Color.fromARGB(255, 255, 255, 255)
                                            .withOpacity(0.2),
                                    borderRadius: BorderRadius.circular(21),
                                  ),
                                  child: Center(
                                    child: Text(
                                      'A面',
                                      style: TextStyle(
                                          fontSize: 16.w,
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8.w),
                                Container(
                                  width: dialogWidth,
                                  child: BoardWidget(
                                    boardKey: GlobalKey(),
                                    aspectRatio: aspectRatio,
                                    elements: templateModelA.value!
                                        .toBoardElements(
                                            scale: dialogWidth / Get.size.width,
                                            maxHeight: previewHeight),
                                    canvasSize:
                                        Size(dialogWidth, previewHeight),
                                    onElementSelected: (_) {},
                                    onElementPositionChanged: (_, __) {},
                                    editable: false,
                                    textContents: selectedMembers
                                            .first.memberInfoList
                                            ?.where((e) =>
                                                e.type == 'A' ||
                                                e.type == 'AB' ||
                                                (sampleValue.value == 0 &&
                                                    e.type == 'B'))
                                            .map((e) => e.value ?? '')
                                            .toList() ??
                                        [],
                                  ),
                                ),
                                SizedBox(height: 16.w),
                              ],
                            ),
                          // Fix B面预览
                          if (sampleValue.value != 2 &&
                              templateModelB.value != null)
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  width: 104.w,
                                  height: 34.h,
                                  decoration: BoxDecoration(
                                    color:
                                        const Color.fromARGB(255, 255, 255, 255)
                                            .withOpacity(0.2),
                                    borderRadius: BorderRadius.circular(21),
                                  ),
                                  child: Center(
                                    child: Text(
                                      'B面',
                                      style: TextStyle(
                                          fontSize: 16.w,
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8.w),
                                Container(
                                  width: dialogWidth,
                                  child: BoardWidget(
                                    boardKey: GlobalKey(),
                                    aspectRatio: aspectRatio,
                                    elements: templateModelB.value!
                                        .toBoardElements(
                                            scale: dialogWidth / Get.size.width,
                                            maxHeight: previewHeight),
                                    canvasSize:
                                        Size(dialogWidth, previewHeight),
                                    onElementSelected: (_) {},
                                    onElementPositionChanged: (_, __) {},
                                    editable: false,
                                    textContents: selectedMembers
                                            .first.memberInfoList
                                            ?.where((e) =>
                                                e.type == 'B' ||
                                                e.type == 'AB' ||
                                                (sampleValue.value == 0 &&
                                                    e.type == 'A'))
                                            .map((e) => e.value ?? '')
                                            .toList() ??
                                        [],
                                  ),
                                ),
                                SizedBox(height: 16.w),
                              ],
                            ),
                        ],
                      ),
                      Positioned(
                        top: 19.h,
                        left: 16.w,
                        child: GestureDetector(
                          onTap: () => Get.back(),
                          child: Image.asset(
                            'assets/images/Group 1321318702@2x.png',
                            width: 28.w,
                            height: 28.w,
                          ),
                        ),
                      ),
                    ],
                  )),
            );
          },
        ),
      ),
      barrierDismissible: true,
    );
  }

  selectDeviceByNfc() async {
    bool isAvailable = await NfcManager.instance.isAvailable();
    if (!isAvailable) {
      ToastUtils.showError(
          AppLocalizations.of(Get.context!)!.translate('nfc_not_available'));
      return;
    }
    Get.bottomSheet(
      GetBuilder<AddDeviceController>(
        init: AddDeviceController(),
        initState: (_) {},
        builder: (AddDeviceController controller) {
          return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(18.r),
                  topRight: Radius.circular(18.r)),
            ),
            height: Get.height * 0.85,
            child: AddDeviceView(),
          );
        },
      ),
      enterBottomSheetDuration: 300.milliseconds,
      exitBottomSheetDuration: 300.milliseconds,
      backgroundColor: Colors.white,
      elevation: 1,
      settings: RouteSettings(name: Routes.ADD_DEVICE, arguments: {
        'group': AppLocalizations.of(Get.context!)!
            .translate('device_default_group'),
        'groupId': '0',
        'type': 'nfc',
        'from': 'cast'
      }),
      ignoreSafeArea: false,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r))),
    );
  }
}
